package com.mxt.moviedemo.controller;

import com.mxt.moviedemo.entity.User;
import com.mxt.moviedemo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @RequestMapping("login")
    public Map<String, Object> login(@RequestParam("loginType") String loginType,
                                     @RequestParam("identifier") String identifier,
                                     @RequestParam("password") String password) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = null;
            if ("phone".equals(loginType)) {
                user = userService.loginForPhone(identifier, password);
            } else if ("email".equals(loginType)) {
                user = userService.loginForEmail(identifier, password);
            }

            if (user != null) {
                // 登录成功，返回包含用户名和跳转信息的数据
                result.put("success", true);
                result.put("username", user.getUname());
                result.put("redirectUrl", "/successPage");
            } else {
                result.put("success", false);
                result.put("error", "手机号/邮箱或密码错误");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "登录失败：" + e.getMessage());
        }
        return result;
    }

    @PostMapping("register")
    public Map<String, Object> register(@RequestBody User user) {
        logger.info("Received user for registration: {}", user);
        Map<String, Object> result = new HashMap<>();
        try {
            // 简单的表单验证
            if (user.getUname() == null || user.getPassword() == null) {
                result.put("success", false);
                result.put("message", "用户名和密码不能为空");
                return result;
            }
            user.setRole("用户");
            user.setBalance("0");
            int rows = userService.registerUser(user);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "注册成功");
            } else {
                result.put("success", false);
                result.put("message", "注册失败");
            }
        } catch (Exception e) {
            logger.error("Registration error: ", e);
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
        }
        return result;
    }
}